/*
 * Copyright (c) 2016. For Intelligent Group.
 */

package com.intelligent.mts.da.handler;


import com.intelligent.mts.core.utils.AppConst;
import com.intelligent.mts.da.message.ReceiveMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Created by Julia.Zhou on 2016/07/20.
 */
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    public static Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("Start heartbeat process.");
        String returnMessage = "";
        ReceiveMessage receiveMessage = (ReceiveMessage) msg;
        String station = receiveMessage.getStationId();
        try{
            returnMessage = AppConst.START_HEARTBEAT + AppConst.SEPARATOR + station + AppConst.SEPARATOR + AppConst.RESULT_OK + AppConst.END_FLAG;
            ctx.writeAndFlush(returnMessage);
            logger.info("Process finish, return:[{}]", returnMessage);
        } catch (Exception e) {
            returnMessage = AppConst.START_HEARTBEAT + AppConst.SEPARATOR + station + AppConst.SEPARATOR + AppConst.RESULT_NG + AppConst.END_FLAG;
            ctx.writeAndFlush(returnMessage);
            logger.info("Process finish, return:[{}]", returnMessage);
            logger.error("Exception found:[{}]", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warn("Unexpected exception from com.intelligent.mts.da.handler " + cause);
        ctx.fireExceptionCaught(cause);
    }
}
